package com.atguigu.gmall.juc.atomic;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 陈昆昆
 * @version 1.0
 * @date 2020/6/2 20:39
 */
public class Wait {
    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    private int num = 0;

    public void increment(){
        lock.lock();
        try{
            while (num!=0){
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            num++;
            condition.signalAll();
            System.out.println(Thread.currentThread().getName()+"---"+num);
        }finally {
            lock.unlock();
        }
    }

    public void decrement(){
        lock.lock();
        try{
            while (num==0){
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            num--;
            condition.signalAll();
            System.out.println(Thread.currentThread().getName()+"---"+num);
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
       Wait wait = new Wait();
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                wait.increment();
            },"AA").start();
        }
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                wait.decrement();
            },"BB").start();
        }
    }
}
